//
//  YSEmoticonTopBar.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/21.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSEmoticonTopBar.h"
#import "YSEmoticonKeyBoard.h"
#import "NSAttributedString+YSAdd.h"
#import "YSEmoticion.h"

/// 表情键盘高度
static CGFloat const kEmotionKeyBoardHeight = 230;
/// 输入框最大高度
static CGFloat const kMaxHeight = 100;
// 输入框的高度
static CGFloat const kTextViewH = 34;
static CGFloat const kVMarin = 8;
static CGFloat const kHMargin = 10;
// 顶部工具条的高度
#define kTopBarH (kTextViewH + 2 * kVMarin)

// 键盘切换按钮的宽高
static CGFloat const kEmotionButtonWH = 30;

@interface YSEmoticonTopBar () <UITextViewDelegate, YSEmoticonKeyBoardDelegate>

@property (nonatomic, strong) UIView *topLine;
@property (nonatomic, strong) UIView *bottomLine;

@property (nonatomic, assign) CGRect keyboardFrame;
@property (nonatomic, assign) BOOL isKeyBoardChange;


// 表情大小需要根据字体计算
@property(nonatomic, assign) CGFloat emotionSize;

@end

@implementation YSEmoticonTopBar

#pragma mark - public method
- (void)resetSubviews {
    [self textViewDidChange:self.textView];
}

#pragma mark - life cycle
- (instancetype)init {
    if (self = [super init]) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    self.backgroundColor = YSEmoticonRGB(250, 250, 250);
    self.userInteractionEnabled = YES;
    self.emotionSize = [self heightWithFont:self.textView.font];
    
    [self addSubviews];
    [self layoutViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)addSubviews {
    [self addSubview:self.textView];
    [self addSubview:self.emotionButton];
    [self addSubview:self.topLine];
    [self addSubview:self.bottomLine];
}

- (void)layoutViews {
    CGFloat textViewW = YSEmoticonScreenWidth - kHMargin * 3 - kEmotionButtonWH;
    self.textView.frame = CGRectMake(kHMargin, kVMarin, textViewW, kTextViewH);
    self.frame = CGRectMake(0, YSEmoticonScreenHeight - kTopBarH, YSEmoticonScreenWidth, kTopBarH);
    self.emotionButton.frame = CGRectMake(CGRectGetMaxX(self.textView.frame) + kHMargin, CGRectGetHeight(self.frame) - kHMargin - kEmotionButtonWH, kEmotionButtonWH, kEmotionButtonWH);
    self.topLine.frame = CGRectMake(0, 0, YSEmoticonScreenWidth, 0.5);
    self.bottomLine.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 0.5, YSEmoticonScreenWidth, 0.5);
}

#pragma mark - event response
- (void)keyboardWillChangeFrame:(NSNotification *)noti {
    NSDictionary *userInfo = noti.userInfo;
    self.duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    self.keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    if (self.isKeyBoardChange) {
        return;
    }
        
    if (self.keyboardFrame.origin.y >= YSEmoticonScreenHeight) {
        // 复原表情键盘
        self.textView.inputView = nil;
        self.emotionButton.selected = NO;
    }
    
    [self textViewDidChange:self.textView];
}

- (void)clickEmotionButton:(UIButton *)button {
    button.selected = !button.selected;
    
    // 切换键盘
    UITextRange *range = self.textView.selectedTextRange;
    self.isKeyBoardChange = YES;
    [self.textView resignFirstResponder];
    self.textView.inputView = self.textView.inputView == nil ? self.emoticonKeyBoard : nil;
    self.isKeyBoardChange = NO;
    [self.textView becomeFirstResponder];
    self.textView.selectedTextRange = range;    
}

#pragma mark - private method
// 根据字体计算表情的高度
- (CGFloat)heightWithFont:(UIFont *)font {
    if (!font){ font = [UIFont systemFontOfSize:17]; }
    NSDictionary *dict = @{NSFontAttributeName:font};
    CGSize maxsize = CGSizeMake(100, MAXFLOAT);
    CGSize size = [@"/" boundingRectWithSize:maxsize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size.height;
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        if ([self.delegate respondsToSelector:@selector(emoticonTopBar:sendMessage:)]) {
            NSString *message = [self.textView.attributedText getPlainString];
            if (message.length > 0) {
                [self.delegate emoticonTopBar:self sendMessage:message];
                
                // 删除字符串
                self.textView.text = @"";
                [self resetSubviews];
            }
        }
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView {
    CGFloat width   = CGRectGetWidth(textView.frame);
    CGSize newSize  = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    CGRect maxFrame = textView.frame;
    maxFrame.size   = CGSizeMake(width, kMaxHeight);
    newFrame.size   = CGSizeMake(width, newSize.height);
    
    if (newSize.height <= kMaxHeight) {
        textView.scrollEnabled = NO;
    } else {
        newFrame = maxFrame;
        textView.scrollEnabled = YES;
    }
    
    if (self.textView.text.length > 0) {
        [UIView animateWithDuration:self.duration animations:^{
            self.ys_height = CGRectGetMaxY(newFrame) + kVMarin;
            self.ys_y = self.keyboardFrame.origin.y - CGRectGetMaxY(newFrame) - kVMarin;
            textView.frame = newFrame;
            self.bottomLine.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 0.5, YSEmoticonScreenWidth, 0.5);
            self.topLine.frame = CGRectMake(0, 0, YSEmoticonScreenWidth, 0.5);
            self.emotionButton.ys_bottom = CGRectGetHeight(self.frame) - kHMargin;
            
            if ([self.delegate respondsToSelector:@selector(emoticonTopBarUpdateSuperView)]) {
                [self.delegate emoticonTopBarUpdateSuperView];
            }
        }];
    } else {
        self.ys_height = CGRectGetMaxY(newFrame) + kVMarin;
        self.ys_y = self.keyboardFrame.origin.y - CGRectGetMaxY(newFrame) - kVMarin;
        textView.frame = newFrame;
        self.bottomLine.frame = CGRectMake(0, CGRectGetHeight(self.frame) - 0.5, YSEmoticonScreenWidth, 0.5);
        self.topLine.frame = CGRectMake(0, 0, YSEmoticonScreenWidth, 0.5);
        self.emotionButton.ys_bottom = CGRectGetHeight(self.frame) - kHMargin;
        
        if ([self.delegate respondsToSelector:@selector(emoticonTopBarUpdateSuperView)]) {
            [self.delegate emoticonTopBarUpdateSuperView];
        }
    }
}

#pragma mark - YSEmoticonKeyBoardDelegate
- (void)emoticonKeyBoard:(YSEmoticonKeyBoard *)emoticonKeyBoard clickEmoticion:(YSEmoticion *)emoticion {
    //创建附件
    YSTextAttachment *emojiTextAttachment = [[YSTextAttachment alloc] init];
    emojiTextAttachment.emojiTag = emoticion.emoticonName;
    // 取到表情对应的表情
    NSString *imageName = emoticion.emoticonImage;
    // 给附件设置图片
    emojiTextAttachment.image = [UIImage imageNamed:imageName];
    // 给附件设置尺寸
    emojiTextAttachment.bounds = CGRectMake(0, -4, self.emotionSize, self.emotionSize);
    // textview插入富文本，用创建的附件初始化富文本
    [self.textView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:emojiTextAttachment] atIndex:self.textView.selectedRange.location];
    self.textView.selectedRange = NSMakeRange(self.textView.selectedRange.location + 1, self.textView.selectedRange.length);
    /// 上面这个方法会改变字体大小???
    self.textView.font = [UIFont systemFontOfSize:17];
    // 重设输入框字体
    [self resetTextStyle];
}

- (void)resetTextStyle {
    NSRange wholeRange = NSMakeRange(0, self.textView.textStorage.length);
    [self.textView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [self.textView.textStorage addAttribute:NSFontAttributeName value:self.textView.font range:wholeRange];
    [self.textView scrollRectToVisible:CGRectMake(0, 0, self.textView.contentSize.width, self.textView.contentSize.height) animated:NO];
    [self resetSubviews];
}

- (void)emoticonKeyBoard:(YSEmoticonKeyBoard *)emoticonKeyBoard clickDelete:(YSEmoticion *)emoticion {
    [self.textView deleteBackward];
}

- (void)emoticonKeyBoard:(YSEmoticonKeyBoard *)emoticonKeyBoard clickSend:(UIButton *)sendButton {
    if ([self.delegate respondsToSelector:@selector(emoticonTopBar:sendMessage:)]) {
        NSString *message = [self.textView.attributedText getPlainString];
        if (message.length > 0) {
            [self.delegate emoticonTopBar:self sendMessage:message];
            
            // 删除字符串
            self.textView.text = @"";
            [self textViewDidChange:self.textView];
        }
    }
}

#pragma mark - 懒加载
- (YSEmoticonKeyBoard *)emoticonKeyBoard {
    if (!_emoticonKeyBoard) {
        _emoticonKeyBoard = [[YSEmoticonKeyBoard alloc] initWithFrame:CGRectMake(0, 0, YSEmoticonScreenWidth, kEmotionKeyBoardHeight)];
        _emoticonKeyBoard.delegate = self;
    }
    return _emoticonKeyBoard;
}

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.returnKeyType = UIReturnKeySend;
        _textView.layer.cornerRadius = 5;
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = YSEmoticonRGB(221, 221, 221).CGColor;
        _textView.scrollEnabled = YES;
        _textView.font = [UIFont systemFontOfSize:17.0];
        [_textView scrollRangeToVisible:NSMakeRange(_textView.text.length, 1)];
        _textView.delegate = self;
    }
    return _textView;
}

- (UIButton *)emotionButton {
    if (!_emotionButton) {
        _emotionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_emotionButton setImage:[UIImage imageNamed:@"group_topic_expression"] forState:UIControlStateNormal];
        [_emotionButton setImage:[UIImage imageNamed:@"group_topic_keyboard"] forState:UIControlStateSelected];
        [_emotionButton addTarget:self action:@selector(clickEmotionButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _emotionButton;
}

- (UIView *)topLine {
    if (!_topLine) {
        _topLine = [[UIView alloc] init];
        _topLine.backgroundColor = YSEmoticonRGB(215, 215, 225);
    }
    return _topLine;
}

- (UIView *)bottomLine {
    if (!_bottomLine) {
        _bottomLine = [[UIView alloc] init];
        _bottomLine.backgroundColor = YSEmoticonRGB(215, 215, 225);
    }
    return _bottomLine;
}

@end
